/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.business.service.impl;

import me.zhengjie.business.domain.Ymk;
import me.zhengjie.business.domain.vo.KA03;
import me.zhengjie.business.service.dto.YbryDto;
import me.zhengjie.modules.mnt.domain.Database;
import me.zhengjie.modules.mnt.repository.DatabaseRepository;
import me.zhengjie.modules.mnt.util.SqlUtils;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.business.repository.YmkRepository;
import me.zhengjie.business.service.YmkService;
import me.zhengjie.business.service.dto.YmkDto;
import me.zhengjie.business.service.dto.YmkQueryCriteria;
import me.zhengjie.business.service.mapstruct.YmkMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.util.IdUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author xiahongbo
* @date 2022-04-14
**/
@Service
@RequiredArgsConstructor
public class YmkServiceImpl implements YmkService {

    private final DatabaseRepository databaseRepository;
    private final YmkRepository ymkRepository;
    private final YmkMapper ymkMapper;

    @Override
    public Map<String,Object> queryAll(YmkQueryCriteria criteria, Pageable pageable){
        Page<Ymk> page = ymkRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(ymkMapper::toDto));
    }

    @Override
    public List<YmkDto> queryAll(YmkQueryCriteria criteria){
        return ymkMapper.toDto(ymkRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public YmkDto findById(String bisYmkId) {
        Ymk ymk = ymkRepository.findById(bisYmkId).orElseGet(Ymk::new);
        ValidationUtil.isNull(ymk.getBisYmkId(),"Ymk","bisYmkId",bisYmkId);
        return ymkMapper.toDto(ymk);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public YmkDto create(Ymk resources) {
        resources.setBisYmkId(IdUtil.simpleUUID()); 
        return ymkMapper.toDto(ymkRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Ymk resources) {
        Ymk ymk = ymkRepository.findById(resources.getBisYmkId()).orElseGet(Ymk::new);
        ValidationUtil.isNull( ymk.getBisYmkId(),"Ymk","id",resources.getBisYmkId());
        ymk.copy(resources);
        ymkRepository.save(ymk);
    }

    @Override
    public void deleteAll(String[] ids) {
        for (String bisYmkId : ids) {
            ymkRepository.deleteById(bisYmkId);
        }
    }

    @Override
    public void download(List<YmkDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (YmkDto ymk : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public List<KA03> queryAll() {

        Database database = databaseRepository.findById("746d5e3732114d0cb8ee5985a005cb40").orElseGet(Database::new);

        Map<String, Object> map = new HashMap();
        List<KA03> list2 = new ArrayList<>();
        DataSource dataSource = SqlUtils.getDataSource(database.getJdbcUrl(), database.getUserName(), database.getPwd());
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
        } catch (Exception ignored) {}
        try {
            int timeOut = 5;
            if (null == connection || connection.isClosed() || !connection.isValid(timeOut)) {
                //   log.info("connection is closed or invalid, retry get connection!");
                connection = dataSource.getConnection();
            }
            String sql = "select " +
                    "       AKA090, " +
                    "       AKA091, " +
                    "       AKA066, " +
                    "       AKA065, " +
                    "       AKA068, " +
                    "       AAE030, " +
                    "       AAE031, " +
                    "       CKA003, " +
                    "       case " +
                    "         when substr(aka090, 0, 8) = 'JJZHYLHL' then '95' " +
                    "         when substr(aka090, 0, 8) = 'JJZHSHHL' then '94' " +
                    "         else '84'  " +
                    "       end yllb " +
                    "  from GGJK_CAREINSU_KA03 t " +
                    " where aka065 = '1' " +
                    "   and aka090 != 'JJZHFH01' " +
                    "   and aka090 != 'JJZHSHHL000' " +
                    "   and aka090 != 'JJZHYLHL000' " +
                    " order by aka090  ";
            PreparedStatement st = connection.prepareStatement(sql);
            ResultSet rs = st.executeQuery();

            while(rs.next()) {
                KA03 ka03 = new KA03();
                ka03.setAka090("".equals(rs.getString("AKA090")) ? "" : rs.getString("AKA090"));
                ka03.setAka091("".equals(rs.getString("AKA091")) ? "" : rs.getString("AKA091"));
                ka03.setAka066("".equals(rs.getString("AKA066")) ? "" : rs.getString("AKA066"));
                ka03.setAka065("".equals(rs.getString("AKA065")) ? "" : rs.getString("AKA065"));
                ka03.setAka068("".equals(rs.getString("AKA068")) ? "" : rs.getString("AKA068"));
                ka03.setCka003("".equals(rs.getString("CKA003")) ? "" : rs.getString("CKA003"));
                ka03.setYllb("".equals(rs.getString("YLLB")) ? "" : rs.getString("YLLB"));
                list2.add(ka03);
            }
            System.out.println("----------open");
            map.put("content", list2);
            map.put("totalElements", list2.size());
        } catch (Exception e) {
            //    log.error("create connection error, jdbcUrl: {}", jdbcUrl);
            throw new RuntimeException("create connection error, jdbcUrl: " + e.getMessage());
        } finally {
            CloseUtil.close(connection);
            System.out.println("----------close");
        }
        return list2;
    }
}